package com.ruoyi.userSpeechFeatures.service.impl;

import com.ruoyi.userSpeechFeatures.domain.UserSpeechFeatures;
import com.ruoyi.userSpeechFeatures.mapper.UserSpeechFeaturesMapper;
import com.ruoyi.userSpeechFeatures.service.IUserSpeechFeatures;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @program: RuoYi-Vue-master
 * @description:
 * @author: xgw
 * @create: 2025-01-13 19:28
 **/


@Service
public class UserSpeechFeaturesImpl implements IUserSpeechFeatures {

    @Autowired
    private UserSpeechFeaturesMapper userSpeechFeaturesMapper;


    /**
    * @Description: 查询出用户对应的特征值
    * @Param: [userId]
    * @return: com.ruoyi.userSpeechFeatures.domain.UserSpeechFeatures
    * @Author: xgw
    * @Date: 2025/1/13
    */
    @Override
    public UserSpeechFeatures selectUserSpeechFeaturesByUserId(Integer userId) {
        return userSpeechFeaturesMapper.selectUserSpeechFeaturesByUserId(userId);
    }

    /**
     * 插入用户的特征值
     * @param userSpeechFeatures
     * @param videos
     */
    @Override
    public void speechRecognitionFun(UserSpeechFeatures userSpeechFeatures, List<String> videos) {
        try {
            // 构建 ProcessBuilder 来执行 Python 脚本
            // 第一个参数是python.exe程序安装的路径 where python 查看
            // 第二个参数是脚本文件
            // 第3-7个参数为4个音频文件路径
            ProcessBuilder pb = new ProcessBuilder("D:\\software\\python\\python.exe",
                    "src/main/java/com/ruoyi/userSpeechFeatures/py/initLibrosa.py",
                    videos.get(0),videos.get(1),videos.get(2),videos.get(3));
            // 启动进程
            Process process = pb.start();
            // 读取 Python 脚本的标准输出
            BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = stdoutReader.readLine())!= null) {
                System.out.println("STDOUT: " + line);
            }
            // 等待 Python 进程完成
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("Python script executed successfully.");
            } else {
                System.err.println("Python script exited with error code: " + exitCode);
            }
            //将特征值存入mysql中

            userSpeechFeaturesMapper.insertUserSpeechFeatures(userSpeechFeatures);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
